﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Xml;

namespace Marbles.Core.Content.CDN
{
    public class CDNSettingCollection : ICollection<CDNSetting>
    {

        public int Count
        {
            get { return items.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public static string Filename { get { return HttpContext.Current.Server.MapPath(VirtualPath); } }

        public CDNSetting this[int index] { get { return items[index]; } set { items[index] = value; } }

        private List<CDNSetting> items = null;
        private const string VirtualPath = "~/App_Data/CDN/urls.xml";

        public CDNSettingCollection()
        {
            items = new List<CDNSetting>();
            Load();
        }

        public void Load()
        {
            items.Clear();
            if (!File.Exists(Filename)) { return; }

            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(Filename);
            XmlNodeList list = xdoc.GetElementsByTagName("add");

            foreach (XmlNode node in list)
            {
                items.Add(new CDNSetting(node));
            }
        }

        public static CDNSetting Load(string Id)
        {
            if (!File.Exists(Filename)) { return null; }

            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(Filename);
            XmlNodeList list = xdoc.GetElementsByTagName("add");

            foreach (XmlNode node in list)
            {
                CDNSetting value = new CDNSetting(node);
                if (value.Id == Id) { return value; }
            }

            return null;
        }

        public static void Save(CDNSetting setting)
        {
            if (!File.Exists(Filename)) { CreateFile(); }
            bool fnd = false;
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(Filename);

            XmlNodeList root = xdoc.SelectNodes("/cdns/cdn[@name='" + setting.Name + "']");

            if (root.Count > 0)
            {
                foreach (XmlNode node in root[0].ChildNodes)
                {
                    if (node.Attributes["id"].Value == setting.Id)
                    {
                        node.Attributes["default"].Value = setting.DefaultCDN.ToString().ToLower();
                        node.Attributes["url"].Value = setting.Url;
                        node.Attributes["type"].Value = setting.Type;
                        fnd = true;
                        break;
                    }
                }

                if (!fnd)
                {
                    XmlElement newnode = xdoc.CreateElement("add");
                    newnode.Attributes.Append(CreateAttribute(xdoc, "id", setting.Id));
                    newnode.Attributes.Append(CreateAttribute(xdoc, "default", setting.DefaultCDN.ToString().ToLower()));
                    newnode.Attributes.Append(CreateAttribute(xdoc, "url", setting.Url));
                    newnode.Attributes.Append(CreateAttribute(xdoc, "type", setting.Type));
                    root[0].AppendChild(newnode);
                }
            }


            xdoc.Save(Filename);
        }

        private static XmlAttribute CreateAttribute(XmlDocument xdoc, string name, string value)
        {
            XmlAttribute attrib = xdoc.CreateAttribute(name);
            attrib.Value = value;
            return attrib;
        }

        public static void Delete(CDNSetting setting)
        {
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(Filename);
            bool fnd = false;

            XmlNodeList root = xdoc.SelectNodes("/cdns/cdn[@name='" + setting.Name + "']");

            if (root.Count > 0)
            {
                foreach (XmlNode node in root[0].ChildNodes)
                {
                    if (node.Attributes["id"].Value == setting.Id)
                    {
                        node.ParentNode.RemoveChild(node);
                        //xdoc.RemoveChild(node);
                        fnd = true;
                        break;
                    }
                }
            }

            if (fnd) { xdoc.Save(Filename); }
        }

        public static string[] GetSupportedCDNTypes()
        {
            return new String[] {"jquery","jqueryui"};
        }

        private static void CreateFile()
        {
            StreamWriter sw = new StreamWriter(Filename);
            sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            sw.WriteLine("<cdns>");
            foreach (string key in GetSupportedCDNTypes())
            {
                sw.WriteLine("<cdn name=\"" + key + "\">");
                sw.WriteLine("</cdn>");
            }
            sw.WriteLine("</cdns>");
            sw.Flush();
            sw.Close();
        }

        public void Add(CDNSetting item)
        {
            items.Add(item);
        }

        public void Clear()
        {
            items.Clear();
        }

        public bool Contains(CDNSetting item)
        {
            return items.Contains(item);
        }

        public void CopyTo(CDNSetting[] array, int arrayIndex)
        {
            items.CopyTo(array, arrayIndex);
        }

        public bool Remove(CDNSetting item)
        {
            return items.Remove(item);
        }

        public IEnumerator<CDNSetting> GetEnumerator()
        {
            return items.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return items.GetEnumerator();
        }
    }
}